package encryption

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"os"
)
//获取公钥
func GetPKey()string{
	path := "public1.pem"
	file,err :=os.Open(path)
	if err!=nil{
		panic(err)
	}
	defer file.Close()
	info,_ := file.Stat()
	buf :=make([]byte,info.Size())
	file.Read(buf)
	str := string(buf)
	return str
	//fmt.Println(string(buf))
}

func DumpPrivateKeyBase64(privatekey *rsa.PrivateKey) (string, error) {
	var keybytes []byte = x509.MarshalPKCS1PrivateKey(privatekey)

	keybase64 := base64.StdEncoding.EncodeToString(keybytes)
	return keybase64, nil
}
func GenerateRSAKey(bits int){
	privateKey, err := rsa.GenerateKey(rand.Reader, bits)
	if err!=nil{
		panic(err)
	}
	X509PrivateKey := x509.MarshalPKCS1PrivateKey(privateKey)
	privateFile, err := os.Create("private1.txt")
	if err!=nil{
		panic(err)
	}
	defer privateFile.Close()

	privateBlock:= pem.Block{Type: "RSA Private Key",Bytes:X509PrivateKey}
	//将数据保存到文件
	pem.Encode(privateFile,&privateBlock)


	publicKey:=privateKey.PublicKey

	X509PublicKey,err:=x509.MarshalPKIXPublicKey(&publicKey)
	if err!=nil{
		panic(err)
	}

	publicFile, err := os.Create("public1.pem")
	if err!=nil{
		panic(err)
	}
	defer publicFile.Close()
	publicBlock:= pem.Block{Type: "RSA Public Key",Bytes:X509PublicKey}
	//保存到文件
	pem.Encode(publicFile,&publicBlock)
}

//RSA加密
func RSA_Encrypt(plainText []byte,path string)[]byte{

	file,err:=os.Open(path)
	if err!=nil{
		panic(err)
	}
	defer file.Close()

	info, _ := file.Stat()
	buf:=make([]byte,info.Size())
	file.Read(buf)

	block, _ := pem.Decode(buf)

	publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err!=nil{
		panic(err)
	}

	publicKey:=publicKeyInterface.(*rsa.PublicKey)
	//对明文进行加密
	cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, plainText)
	if err!=nil{
		panic(err)
	}
	//返回密文
	return cipherText
}

//RSA解密
func RSA_Decrypt(cipherText []byte,path string) []byte{
	//打开文件
	file,err:=os.Open(path)
	if err!=nil{
		panic(err)
	}
	defer file.Close()
	//获取文件内容
	info, _ := file.Stat()
	buf:=make([]byte,info.Size())
	file.Read(buf)

	block, _ := pem.Decode(buf)

	privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err!=nil{
		panic(err)
	}

	plainText,_:=rsa.DecryptPKCS1v15(rand.Reader,privateKey,cipherText)
	//返回明文
	return plainText
}

